#include "stdafx.h"
#include "GameApplication.h"


#include "..\TwEngine\TwEngineDx.h"
#include "..\TwEngine\TwShaderEffect.h"
#include <d3dx9tex.h>

#pragma  comment(lib, "d3d9.lib")
#pragma  comment(lib, "d3dx9.lib")

#define SCREEN_WIDTH		800
#define SCREEN_HEIGHT		700

TwEngineDx* g_Render = NULL;

void TwGameApplication::CreateGameWnd(HWND hwnd)
{
	m_hwnd = hwnd;
	if(InitDevice() == FALSE)
		return;
	if(InitEngine() == FALSE)
		return ;
}
BOOL TwGameApplication::InitDevice()
{
	if( NULL == ( g_pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
		return FALSE;

	D3DPRESENT_PARAMETERS d3dpp; 
	ZeroMemory( &d3dpp, sizeof(d3dpp) );
	d3dpp.Windowed = TRUE;
	d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;


	if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hwnd,
		D3DCREATE_HARDWARE_VERTEXPROCESSING,
		&d3dpp, &g_pd3dDevice ) ) )
	{
		return FALSE;
	}
	return TRUE;
}
BOOL TwGameApplication::InitEngine()
{
	g_Render = new TwEngineDx();
	if(g_Render &&(g_pd3dDevice!= NULL))
	{
		g_Render->SetDevice(g_pd3dDevice);
		g_Render->InitMgr();
		g_Render->InitTerrainMgr();
		return TRUE;
	}
	return FALSE;
}
void TwGameApplication::InitCamera()
{

}

void TwGameApplication::Update()
{
	static float fPreTime = static_cast<float>(GetTickCount());
	float fCurrentTime = static_cast<float>(GetTickCount());
	float fElapsedTime = (fCurrentTime - fPreTime)*0.001f;
	LogicFrame(fElapsedTime);
	RenderFrame(fElapsedTime);
	fPreTime = fCurrentTime;
}
void TwGameApplication::LogicFrame(float fElapsedTime)
{
	if(g_Render)
	{
		g_Render->UpdateCamera(fElapsedTime);
	}
}
void TwGameApplication::RenderFrame(float fElapsedTime)
{

}
void TwGameApplication::Render()
{
	if(g_Render)
	{
		if (g_Render->BeginRender())
		{
			g_Render->Render();
			g_Render->EndRender();
		}
	}
}
void TwGameApplication::HandleMsg( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
	if(g_Render)
		g_Render->MsgHandle(hWnd, msg, wParam, lParam);
}

bool TwGameApplication::PickTerrain()
{
	return false;
}
bool TwGameApplication::PickEntity()
{
return false;
}
void TwGameApplication::Clear()
{

}